// 小程序发版
const ci = require('miniprogram-ci');
const path = require('path');
// 获取命令行参数 
const argv = require('yargs').argv;

let appid = "wx6197bcc879fe2e4a"
let version = '1.0.0'
let desc = ''
let pagePath = 'pages/index/index'
let searchQuery = ''
let projectPath = './dist'
return (async () => {
    if (argv.appid) {
        appid = argv.appid
    }
    if (argv.version) {
        version = argv.version
    }
    if (argv.desc) {
        desc = argv.desc
    }
    if (argv.projectPath) {
        projectPath = argv.projectPath
    }
    if (argv.pagePath) {
        pagePath = argv.pagePath
    }
    if (argv.searchQuery) {
        searchQuery = argv.searchQuery
    }
    // 注意： new ci.Project 调用时，请确保项目代码已经是完整的，避免编译过程出现找不到文件的报错。
    const project = new ci.Project({
        appid: appid,
        type: 'miniProgram',
        projectPath: path.join(__dirname, projectPath), // 项目路径
        privateKeyPath: path.join(__dirname, `private/./private.${appid}.key`), // 私钥的路径
        ignores: ['node_modules/**/*'],
    })
    // 生成二维码
    const previewResult = await ci.preview({
        project,
        desc, // 此备注将显示在“小程序助手”开发版列表中
        setting: {
            es6: true,
        },
        qrcodeFormat: 'image',
        qrcodeOutputDest: path.join(__dirname, '/qrcode/destination.jpg'),
        onProgressUpdate: console.log,
        pagePath: pagePath, // 预览页面
        searchQuery: searchQuery, // 预览参数 [注意!]这里的`&`字符在命令行中应写成转义字符`\&`
    })
    console.log('previewResult', previewResult)
    console.log('等待5秒后 开始上传')
    // 开始上传
    let s = 5
    let timer = setInterval(async () => {
        --s
        console.log(`${s}秒`)
        if (s == 0) {
            clearInterval(timer);
            timer = undefined
            const uploadResult = await ci.upload({
                project,
                version,
                desc: desc,
                setting: {
                    es6: false, // es6 转 es5
                    disableUseStrict: true,
                    autoPrefixWXSS: true, // 上传时样式自动补全
                    minifyJS: true,
                    minifyWXML: true,
                    minifyWXSS: true,
                }
            })
            console.log('uploadResult', uploadResult)
        }
    }, 1000);
})()
